<template>
	<view class="content">
		<nav-bar title="我的订单" :showLeftIcon="false"></nav-bar>
		<scroll-view scroll-x :style="{ backgroundColor: '#c27e15' }">
			<view class="tabs-box">
				<view v-for="(item, index) in tabList" :key="index"
					:class="['tabs-item', tabActive === item.value ? 'active-item' : '']" @click="clickTabsItem(item)">
					<view class="item">{{ item.label }}</view>
					<view v-if="tabActive === item.value" class="bottom-line"></view>
				</view>
			</view>
		</scroll-view>
		<you-scroll class="scroll" :loadingHeight="loadingHeight" :mainHeight="mainHeight" :isAllData="isAllData"
			:isRequestSuccess="isRequestSuccess" @onRefresh="onRefresh" @loadMore="loadMore">
			<template>
				<view v-if="isLoading" class="common-loading">
					<image class="loading-img" :src="baseIconUrl + 'icon_loading.png'" />
				</view>
				<order-list v-else-if="orderList && orderList.length" :orderList="orderList" :orderStatus="tabActive"
					:slotName="slotName" @slotClick="slotClick" @countdownFinished="handleCountdownFinish"
					@projectOutOrder="projectOutOrder">
					<view class="flexjeac" style="height:100%" v-for="(item, index) in orderList" :slot="`Pay${index}`">
						<view class="btn widthBtn" v-if="item.isPayment === 1&&item.orderSource===1">支付</view>
					</view>
					<view class="flexjeac" style="height:100%" v-for="(item, index) in orderList"
						:slot="`WaitServe${index}` || `All${index}`">
						<view class="btn" @click="waitServeBtn = 'clickEditTime'" v-if="item.orderStatus === 1">修改预约时间
						</view>
						<!-- <view class="btn" @click="waitServeBtn = 'clickApplyBack'" v-if="item.orderStatus === 1">申请退单
						</view> -->
					</view>
					<!-- <view class="flexjeac" style="height:100%" v-for="(item, index) in orderList"
						:slot="`Evaluate${index}`">
						<view class="btn widthBtn">去评价</view>
					</view> -->
					<view class="flexjeac" style="height:100%" v-for="(item, index) in orderList"
						:slot="`AnotherOrder${index}`">
						<view class="btn widthBtn" v-if="item.orderStatus === 4">再来一单</view>
					</view>
				</order-list>
				<view v-else class="common-no-data">
					<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
					<view class="text">暂无订单</view>
				</view>
			</template>
		</you-scroll>
		<u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="datetimeValue" mode="datetime"
			:visibleItemCount="9" @confirm="datetimeConfirm" @cancel="datetimeShow=false"
			:formatter="formatter"></u-datetime-picker>
		<you-popup :popupVisible="popupVisible" :titleSlot="true" popupType="bottom" dialogWidth="100%" :showBtn="false"
			:safeArea="false" @popupClose="popupVisible = false">
			<template slot="popupTitle">
				<view class="popup-title">
					<view class="title-text">选择评价技师</view>
					<view class="city-box"></view>
				</view>
			</template>
			<view slot="popupContent" class="tech-content">
				<view class="tech-item" v-for="(item, index) in evaluateList" :key="index" @click="clickTechItem(item)">
					<view class="label">{{ item.name }}</view>
					<view class="check-box">
						<uni-icons v-if="evaluateTechId === item.id" type="checkbox-filled" color="#c27e15"
							size="24"></uni-icons>
						<uni-icons v-else type="circle" color="#9e9e9e" size="24"></uni-icons>
					</view>
				</view>
				<view class="popup-button" @click="clickToEvaluate">去评价</view>

			</view>
		</you-popup>
		<you-popup :popupVisible="applyDialog" popupTitle="退单确认" :safeArea="false" @popupClose="applyDialog = false"
			@cancel="applyDialog = false" @confirm="confirmOutOrder">
			<view slot="popupContent" class="out-content">
				<view>退单可能会扣除一些损耗费，确认要申请退单吗？</view>
			</view>
		</you-popup>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/index.vue'
	import YouScroll from '@/components/you-scroll/index'
	import YouPopup from '@/components/you-popup2'
	import OrderList from '../../subPages/components/orderList'
	import api_order from '@/api/order'
	import pageConfig from '@/config'

	export default {
		components: {
			NavBar,
			YouPopup,
			YouScroll,
			OrderList
		},
		data() {
			return {
				baseImgUrl: pageConfig.baseImgUrl,
				baseIconUrl: pageConfig.baseIconUrl,
				tabActive: 1,
				tabList: [
					// { label: '待支付', value: 0, slotName: 'Pay' },
					{
						label: '待服务',
						value: 1,
						slotName: 'WaitServe'
					},
					{
						label: '服务中',
						value: 2,
						slotName: null
					},
					{
						label: '待评价',
						value: 3,
						slotName: 'Evaluate'
					},
					{
						label: '已完成',
						value: 4,
						slotName: 'AnotherOrder'
					},
					{
						label: '已退单',
						value: 5,
						slotName: null
					},
				],
				mainHeight: '',
				datetimeShow: false,
				datetimeValue: Number(new Date()),
				columns: [
					[],
					[],
					[],
				],
				defaultIndex: [], // 设置默认选中值为第一列的第二项和第二列的第三项
				loadingHeight: '',
				pageNum: 1,
				pageSize: 10,
				total: 0,
				orderList: [],
				slotName: 'WaitServe',
				status: {
					0: {
						title: '待服务',
						color: '#C27E15'
					},
					1: {
						title: '部分待服务',
						color: '#C27E15'
					},
					2: {
						title: '服务中',
						color: '#FF0000'
					},
				},
				waitServeBtn: '',
				alCompleteBtn: '',
				popupVisible: false,
				operateId: '',
				evaluateList: [],
				evaluateTechDetail: {},
				evaluateTechId: '',
				isAllData: false,
				isRequestSuccess: false,
				isLoading: false,
				applyDialog: false,
				outOrder: null,
				outOrderType: '',
				orderId: null,
			}
		},
		onShow() {
			this.popupVisible = false
			if (uni.getStorageSync('App-Token')) {
				this.tabActive = 1
				this.slotName = 'WaitServe'
				this.pageNum = 1
				this.orderList = []
				this.getOrderList()
			}
			var currentDate = new Date();
			// 获取当前月份
			var currentMonth = currentDate.getMonth() + 1;
			this.currentMonth = currentMonth < 10 ? `0${currentMonth}` : currentMonth; // 补零使月份两位数
			// 获取该月的天数
			var currentYear = currentDate.getFullYear();
			this.currentYear = currentYear
			const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
			var daysArray = Array.from({
				length: daysInMonth
			}, (_, i) => i + 1);
			var houreArray = Array.from({
				length: 24
			}, (_, i) => i + 1);
			this.columns[0] = daysArray
			this.columns[1] = houreArray
			this.columns[2] = [0, 10, 20, 30, 40, 50]
		},
		onLoad() {
			this.mainHeight = this.$store.getters.heightData.mainSearchHeight.split('px')[0] - 10 + 'px'
			this.loadingHeight = this.$store.getters.heightData.mainHeight.split('px')[0] - 70 + 'px'
		},
		methods: {
			clickTabsItem(item) {
				console.log(item)
				this.tabActive = item.value
				this.slotName = item.slotName
				this.pageNum = 1
				this.orderList = []
				this.getOrderList()
			},
			getOrderList() {
				this.isLoading = true
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					userId: uni.getStorageSync('userInfo').id,
					orderStatus: this.tabActive,
					isDelete: 0
				}
				if (this.tabActive !== 0) {
					// params.orderStatus = this.tabActive
					params.isPayment = 2
				} else {
					params.isPayment = 1
				}
				api_order.fetchOrderList(params).then(res => {
					this.isLoading = false
					if (res.code !== 200) return
					res.rows.forEach(item => {
						const createTime = new Date(item.createTime)
						const targetTime = new Date(createTime.getTime() + 3 * 60 *
							1000) // 将 createTime 加上3分钟得到目标时间
						const currentTime = new Date()
						const timeDifferenceInSeconds = Math.floor((targetTime - currentTime) /
							1000) // 计算目标时间与当前时间的秒数差
						item.countdownSeconds =
							timeDifferenceInSeconds // 将计算出的倒计时秒数存储在 item 对象的 countdownSeconds 字段中
					})

					this.orderList.push(...res.rows)
					this.total = res.total
					this.isRequestSuccess = true
				}).catch(err => {
					this.isLoading = false
				})
			},
			slotClick(item, funcName) {
				console.log(item, funcName);
				this[funcName](item)
			},
			handleCountdownFinish(itemId, isPayment) {
				console.log('倒计时结束，ID为：', itemId, isPayment);
				// if(isPayment===1){
				// 	api_order.orderdelete(itemId).then(res => {
				// 	  if (res.code === 200) {
				this.orderList = []
				this.getOrderList()
				// 	  }
				// 	});
				// }
			},
			// 获取可评价技师列表
			getEvaluateTech(params) {
				api_order.fetchEvaluateTech(params).then(res => {
					if (res.code !== 200) return
					if (res.data.length > 1) {
						this.evaluateList = res.data
						this.popupVisible = true
					} else {
						this.evaluateTechId = params.orderId
						this.evaluateTechDetail = res.data[0]
						this.clickToEvaluate()
					}
				})
			},
			clickTechItem(item) {
				this.evaluateTechId = item.id
				this.evaluateTechDetail = item
			},
			// 支付
			clickPay(item) {
				let that = this
				api_order.appWxPayOrder({
					id: item.id
				}).then(res => {
					if (res.code !== 200) return
					uni.removeStorageSync('chooseTechnician')
					if (item.isValue === 2) {
						const payParams = res.data.data
						const resParams = {
							timeStamp: payParams.timestamp,
							nonceStr: payParams.nonceStr,
							package: payParams.package,
							signType: payParams.signType,
							paySign: payParams.paySign
						}
						// 调用微信小程序的支付接口
						uni.requestPayment({
							...resParams,
							success(res) {
								// 支付成功的回调
								this.pageNum = 1
								this.orderList = []
								this.getOrderList()
							},
							fail(res) {
								that.cancelPayment()
								// 支付失败的回调
								console.log('支付失败', res)
							}
						})
					}
					if (item.isValue === 1) {
						uni.showToast({
							title: '储值卡支付成功！',
							icon: 'success',
							mask: true
						})
						this.pageNum = 1
						this.orderList = []
						this.getOrderList()
					}
				})
			},
			// 取消支付函数
			cancelPayment() {
				uni.showToast({
					title: '支付已取消',
					icon: 'none',
					duration: 2000
				})
				this.pageNum = 1
				this.orderList = []
				this.getOrderList()
			},
			// 评价
			clickEvaluate(item) {
				this.getEvaluateTech({
					orderId: item.id
				})
				this.operateId = item.id
			},
			clickToEvaluate() {
				if (!this.evaluateTechId) {
					uni.showToast({
						title: '请选择技师',
						icon: 'none'
					})
					return
				}
				const evaluateTechDetail = encodeURIComponent(JSON.stringify(this.evaluateTechDetail))
				console.log(this.operateId,'this.evaluateTechDetail',this.evaluateTechDetail);
				uni.navigateTo({
					url: `/subPages/order/evaluate?id=${this.operateId}&evaluateTechDetail=${evaluateTechDetail}`
				})
			},
			clickWaitServe(item) {
				console.log(item)
				this[this.waitServeBtn](item)
			},
			// 修改预约时间
			clickEditTime(item) {
				// uni.navigateTo({
				// 	url: `/subPages/order/editReserveTime?id=${item.id}&storeId=${item.storeId}`
				// })

				console.log(item,"item");
				uni.navigateTo({
					url: `/subPages/technician/newAppointment?id=${item.id}`
				})

				// this.orderId=item.id
				// this.datetimeShow = true
				// var currentDate = new Date();
				// // 获取当前月份
				// var currentMonth = currentDate.getMonth() + 1;
				// var currentDay = currentDate.getDate(); // 获取当前日期（1-31）
				// var currentHour = currentDate.getHours(); // 获取当前小时（0-23）
				// var currentMinute = currentDate.getMinutes(); // 获取当前分钟（0-59）
				// var processedMinute = Math.ceil(currentMinute / 10); // 按照规定进行处理
				// this.defaultIndex=[currentDay-1,currentHour-1,processedMinute]
			},
			datetimeConfirm(e) {
				// const day = e.value[0] < 10 ? `0${e.value[0]}` : e.value[0]; // 补零使日期两位数
				// const reserveDate = `${this.currentYear}-${this.currentMonth}-${day}`;
				// const hour =  e.value[1] < 10 ? `0${e.value[1]}` : e.value[1]; // 补零使日期两位数
				// const minute =e.value[2] < 1 ? `00` : e.value[2]; // 补零使日期两位数
				// const reserveTime = `${hour}:${minute}`;
				var date = new Date(this.datetimeValue);
				// 获取年、月、日、时、分
				var year = date.getFullYear();
				var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从 0 开始，需加一并补零
				var day = ('0' + date.getDate()).slice(-2); // 补零
				var hours = ('0' + date.getHours()).slice(-2); // 补零
				var minutes = date.getMinutes();
				// 根据分钟数的范围设置不同的值
				if (minutes >= 0 && minutes <= 10) {
					minutes = 10;
				} else if (minutes >= 11 && minutes <= 20) {
					minutes = 20;
				} else if (minutes >= 21 && minutes <= 30) {
					minutes = 30;
				} else if (minutes >= 31 && minutes <= 40) {
					minutes = 40;
				} else if (minutes >= 41 && minutes <= 50) {
					minutes = 50;
				} else {
					minutes = 0;
					hours = ('0' + (parseInt(hours) + 1)).slice(-2); // 小时加一，并补零
				}

				// 格式化日期和时间字符串
				var formattedDate = year + '-' + month + '-' + day;
				var formattedTime = hours + ':' + ('0' + minutes).slice(-2); // 补零

				// 将格式化后的日期和时间存储在相应的字段中
				var reserveDate = formattedDate;
				var reserveTime = formattedTime;

				// 将格式化后的日期和时间存储在相应的字段中
				var reserveDate = formattedDate;
				var reserveTime = formattedTime;

				const params = {
					orderId: this.orderId,
					subscribeStartTime: reserveDate + ' ' + reserveTime
				}
				api_order.editProjectTime(params).then(res => {
					if (res.code !== 200) return
					uni.showToast({
						title: '已修改预约时间！',
						icon: 'none'
					})
				})
				this.datetimeShow = false
			},
			// 申请整个订单退款
			clickApplyBack(item) {
				this.applyDialog = true
				this.outOrder = item
				this.outOrderType = 'order'
			},
			// 单个项目退单
			projectOutOrder(item) {
				this.applyDialog = true
				this.outOrder = item
				this.outOrderType = 'project'
			},
			confirmOutOrder() {
				if (this.outOrderType === 'project') {
					const params = {
						id: this.outOrder.id
					}
					api_order.projectChargeBack(params).then(res => {
						if (res.code !== 200) return
						uni.showToast({
							title: '退单成功!',
							icon: 'success',
							mask: true
						})
						this.pageNum = 1
						this.orderList = []
						this.getOrderList()
					})
				} else {
					const judgeChargeBack = this.outOrder.zyOrderItemList.filter(zItem => zItem.status !== 1).length
					if (judgeChargeBack) {
						uni.showToast({
							title: '订单中存在已服务项目，请与门店联系',
							icon: 'none',
							mask: true
						})
						return
					}
					api_order.chargeBack({
						id: this.outOrder.id
					}).then(res => {
						if (res.code !== 200) return
						uni.showToast({
							title: '退单成功!',
							icon: 'success',
							mask: true
						})
						this.pageNum = 1
						this.orderList = []
						this.getOrderList()
					})
				}
				this.applyDialog = false
			},
			// 再来一单
			clickAnotherOrder(item) {
				const storeAddress = item.zyStore.provinceString + item.zyStore.cityString + item.zyStore.countyString +
					item.zyStore.detail
				const anotherTransferData = {
					storeId: item.storeId,
					storeName: item.zyStore.storeName,
					regionId: item.zyStore.regionId,
					regionName: item.zyStore.regionName,
					storeAddress,
					openingTime: item.zyStore.openingTime,
					closingTime: item.zyStore.closingTime
				}

				const params = encodeURIComponent(JSON.stringify(anotherTransferData))
				uni.navigateTo({
					url: `/subPages/home/reserveProject?transferData=${params}&anotherReserve=sure`
				})
			},
			// 下拉刷新
			onRefresh() {
				this.pageNum = 1
				this.orderList = []
				this.isAllData = false
				this.isRequestSuccess = false
				this.getOrderList()
			},
			// 上拉加载
			loadMore() {
				if (this.orderList.length < this.total) {
					this.pageNum++
					this.isAllData = false
					this.isRequestSuccess = false
					this.getOrderList()
				} else {
					this.isAllData = true
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.scroll {
		margin-bottom: 100upx;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.tabs-box {
		position: relative;
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 50px;
		padding: 0 28rpx;
		background-color: #C27E15;
		color: #fff;

		.tabs-item {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #fff;
		}

		.active-item {
			font-weight: bold;
		}

		.bottom-line {
			position: absolute;
			bottom: 0;
			width: 80rpx;
			height: 6rpx;
			background: #ffffff;
			border-radius: 3rpx;
		}
	}

	.widthBtn {
		width: 168rpx;
	}

	.popup-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100rpx;
		padding: 0 24rpx;
		border-bottom: 2rpx solid #f2f2f2;
	}

	.tech-content {
		padding: 0 24rpx;

		.tech-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 6rpx;
			border-bottom: 2rpx solid #f2f2f2;

			.label {
				font-weight: bold;
			}
		}

		.popup-button {
			width: 90%;
			height: 80rpx;
			margin: 30rpx auto 0;
			background: linear-gradient(90deg, #EDD3AE 0%, #DCB17F 100%);
			border-radius: 63rpx 63rpx 63rpx 63rpx;
			opacity: 1;
			text-align: center;
			font-size: 30rpx;
			font-family: Source Han Sans CN;
			font-weight: 500;
			line-height: 94rpx;
			margin-bottom: 30rpx;
		}
	}

	.out-content {
		padding: 0 30rpx 40rpx;
		font-size: 28rpx;
		text-align: center;
	}
</style>